package com.tajiang.business.common.utils;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.tajiang.business.common.application.TJApp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017-07-25.
 */

public class CommandTools {

    static String strLastTime;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private static Toast toast;

    /**
     * 弹出toast提示 防止覆盖
     *
     * @param msg
     */
    public static void showShort(String msg) {

        if (toast == null) {
            toast = Toast.makeText(TJApp.getInstance(), msg + "", Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    public static void showLong(String msg) {

        if (toast == null) {
            toast = Toast.makeText(TJApp.getInstance(), msg + "", Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }


    public static boolean hasSdcard() {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 保存方法
     */
    public static File saveBitmap(Bitmap bitmap) {

        Log.e("zd", "保存图片");
        File f = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i("zd", "已经保存");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return f;
    }

    /**
     * 获取当前时间精确到毫秒
     *
     * @return
     */
    public static String initDataTime() {

        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); // 精确到毫秒
        String suffix = fmt.format(new Date());

        strLastTime = TJApp.getInstance().sendTime;

        boolean flag = strLastTime.equals(suffix);
        while (flag == true) {

            suffix = fmt.format(new Date());
            strLastTime = TJApp.getInstance().sendTime;
            flag = strLastTime.equals(suffix);

            try {
                Thread.sleep(300);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return suffix;
    }

    /**
     * json数据格式转换为接口需要类型
     * 通过&拼接
     */
    public static String json2Map(JSONObject jsonObject) {
        if (jsonObject == null) {
            return "";
        }

        HashMap<String, String> data = new HashMap<String, String>();
        // 将json字符串转换成jsonObject
        Iterator it = jsonObject.keys();
        // 遍历jsonObject数据，添加到Map对象

        String strData = null;
        while (it.hasNext()) {
            String key = String.valueOf(it.next());
            String value = null;
            try {

                if (TextUtils.isEmpty((String) jsonObject.get(key))) {
                    value = "";
                } else {
                    value = (String) jsonObject.get(key);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            data.put(key, value);

            try {
                if (TextUtils.isEmpty(strData)) {
                    strData = (key + "=" + URLEncoder.encode(value, "utf-8").toString()) + "&";
                } else {
                    strData = strData + (key + "=" + URLEncoder.encode(value, "utf-8").toString()) + "&";
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return strData;
    }


    public static void test(HashMap<String, String> map) {

        String strData;
        int len = map.size();
        for (int i = 0; i < len; i++) {

        }
    }

    /**
     * 获取当前上下文
     *
     * @return
     */
    public static Activity getGlobalActivity() {

        Class<?> activityThreadClass;
        try {
            activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map<?, ?> activities = (Map<?, ?>) activitiesField.get(activityThread);
            for (Object activityRecord : activities.values()) {
                Class<? extends Object> activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Activity activity = (Activity) activityField.get(activityRecord);
                    return activity;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

//    public static AudioManager getAudioManager(Activity context){
//
//        return (AudioManager)context.getSystemService(Context.LOCATION_SERVICE);
//    }

    /*    *
     * 是否开启了闪光灯
     * @return
     */
    public static boolean isFlashlightOn(Camera camera) {
        try {
            Camera.Parameters parameters = camera.getParameters();
            String flashMode = parameters.getFlashMode();
            if (flashMode.equals(Camera.Parameters.FLASH_MODE_TORCH)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static void openFlash(Camera camera, SurfaceHolder surfaceHolder) {

//        boolean flag = isFlashlightOn(camera);
//        if (flag){
//            CameraManager.get().closeDriver();
//            try {
//                CameraManager.get().openDriver(surfaceHolder);
//                CameraManager.get().startPreview();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }else{
//            Openshoudian(camera);
//        }
    }

    //这是开启方法
    public static void Openshoudian(Camera camera) {
        //异常处理一定要加，否则Camera打开失败的话程序会崩溃
        try {
            Log.d("smile", "camera打开");
//            camera = Camera.open();
        } catch (Exception e) {
            Log.d("smile", "Camera打开有问题");
            Toast.makeText(TJApp.getInstance(), "Camera被占用，请先关闭", Toast.LENGTH_SHORT).show();
        }

        if (camera != null) {
            //打开闪光灯
//            camera.startPreview();
            Camera.Parameters parameter = camera.getParameters();
            parameter.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            camera.setParameters(parameter);
            Log.d("smile", "闪光灯打开");
        }
    }

    //这是关闭方法
    public static void Closeshoudian(Camera camera) {

        if (camera != null) {
            //关闭闪光灯
            Log.d("smile", "closeCamera()");
            camera.getParameters().setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            camera.setParameters(camera.getParameters());
//            camera.stopPreview();
//            camera.release();
//            camera = null;
        }
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 隐藏软键盘
     */
    public static void closeKeyboars(Context context) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 强制关闭软键盘
     */
    public static void hidenKeyboars(Context context, View view) {

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 读取uri所在的图片
     *
     * @param uri
     * @return
     */
    public static Bitmap getBitmapFromUri(Context context, Uri uri) {

        try {

            Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
            return ThumbnailUtils.extractThumbnail(bitmap, 150, 150);
        } catch (Exception e) {
            Log.e("[Android]", e.getMessage());
            Log.e("[Android]", "目录为：" + uri);
            e.printStackTrace();
            return null;
        }
    }

    public static String getBetweenTime(String startTime, String endTime) {

        try {

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat df = new SimpleDateFormat("HH:mm");

            Date dateStart = dateFormat.parse(startTime);
            Date dateEnd = dateFormat.parse(endTime);

            return df.format(dateStart) + "-" + df.format(dateEnd);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public static String handleSendTime(String createTime) {

        try {

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("MM-dd HH:mm");

            Date parse = dateFormat.parse(createTime);
            return dateFormat1.format(parse);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public static void checkBlueTools() {

        // Get local Bluetooth adapter
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();
        // 如果adapter为null,蓝牙设备不支持
        if (bluetoothAdapter == null) {
            ToastUtils.showShort("硬件不支持蓝牙设备");
        } else {
            //打开蓝牙
            if (!bluetoothAdapter.isEnabled()) {
                ToastUtils.showShort("请先打开蓝牙设备");
            } else {

            }
        }
    }

    /**
     * 隐藏卡号几位
     *
     * @param no
     * @param type
     * @return
     */
    public static String hidenCardNo(String no, int type) {

        try {
            if (type == 1) {
                return no.substring(0, 6) + "****" + no.substring(no.length() - 4, no.length());
            } else {
                return "*******" + no.substring(no.length() - 4, no.length());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 获取当前日期
     * @return
     */
    public static String getDate() {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        return formatter.format(curDate);
    }

    public static String getTime() {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        return formatter.format(curDate);
    }

    /**
     * 判断微信是否安装
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {

        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }

        return false;
    }
}
